package com.lxx.jmb2c.controller;

import com.alibaba.fastjson2.JSON;
import com.lxx.jmb2c.common.Result;
import com.lxx.jmb2c.config.QiNiuConfig;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

@Tag(name = "公共接口")
@Slf4j
@RequestMapping("common")
@RestController
public class CommonController {

    @Resource
    private QiNiuConfig qiNiuConfig;


    @PostMapping("upload")
    public Result<String> upload() {
        String newFileName=null;

        //Configuration cfg = Configuration.create(Region.region0());
        Configuration cfg = Configuration.create(Region.huanan());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本


        UploadManager uploadManager = new UploadManager(cfg);

        String accessKey = qiNiuConfig.getAccessKey();
        String secretKey = qiNiuConfig.getSecretKey();
        String bucket = qiNiuConfig.getBucketName();

        String localFilePath = "D:/idea/idea-workspace/jm/jm-b2c-main/doc";

        String key = null;

        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        try {
            Response response = uploadManager.put(localFilePath, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            newFileName= qiNiuConfig.getPrefixUrl()+putRet.key;
            System.out.println(newFileName);
            System.out.println(putRet.hash);
        } catch (QiniuException ex) {
            ex.printStackTrace();
            if (ex.response != null) {
                System.err.println(ex.response);

                try {
                    String body = ex.response.toString();
                    System.err.println(body);
                } catch (Exception ignored) {
                }
            }
        }

        return Result.success(newFileName);
    }
}
